<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商户编号" prop="merchantId">
        <el-select v-model="queryParams.merchantId" placeholder="请选择商户编号" clearable style="width: 200px;">
          <el-option v-for="merchant in merchantList" :key="merchant.id" :label="merchant.name" :value="merchant.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="当前余额" prop="currentBalance">
        <el-input v-model="queryParams.currentBalance" placeholder="请输入当前余额" clearable @keyup.enter="handleQuery"
          style="width: 200px;" />
      </el-form-item>
      <el-form-item label="提现金额" prop="cashWithdrawal">
        <el-input v-model="queryParams.cashWithdrawal" placeholder="请输入提现金额" clearable @keyup.enter="handleQuery"
          style="width: 200px;" />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="queryParams.realName" placeholder="请输入真实姓名" clearable @keyup.enter="handleQuery"
          style="width: 200px;" />
      </el-form-item>
      <el-form-item label="提现时间" prop="withdrawalRecord">
        <el-date-picker clearable v-model="queryParams.withdrawalRecord" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择提现时间" style="width: 200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="提现状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择提现状态" clearable style="width: 200px;">
          <el-option v-for="withdrawalStatus in withdrawalStatuses" :key="withdrawalStatus.value"
            :label="withdrawalStatus.label" :value="withdrawalStatus.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['chy:withdrawal:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['chy:withdrawal:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['chy:withdrawal:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['chy:withdrawal:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="withdrawalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="提现编号" align="center" prop="id" />
      <el-table-column label="商户编号" align="center" prop="merchantId">
        <template #default="scope">
          <span>{{ getMerchantNameById(scope.row.merchantId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前余额(元)" align="center" prop="currentBalance" />
      <el-table-column label="提现金额(元)" align="center" prop="cashWithdrawal" />
      <el-table-column label="真实姓名" align="center" prop="uid">
        <template #default="scope">
          <span>{{ getUserNameById(scope.row.uid) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="银行卡号" align="center" prop="bankCardNumber">
        <template #default="scope">
          <!-- 调用 maskBankCardNumber 函数处理银行卡号 -->
          <span>{{ maskBankCardNumber(scope.row.bankCardNumber) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提现时间" align="center" prop="withdrawalRecord" width="110">
        <template #default="scope">
          <span>{{ parseTime(scope.row.withdrawalRecord, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提现状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.status)">{{ getWithdrawalStatusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['chy:withdrawal:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['chy:withdrawal:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改提现信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="withdrawalRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商户编号" prop="merchantId">
          <el-select v-model="form.merchantId" placeholder="请选择商户编号">
            <el-option v-for="merchant in merchantList" :key="merchant.id" :label="merchant.name"
              :value="merchant.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前余额" prop="currentBalance">
          <el-input v-model="form.currentBalance" placeholder="请输入当前余额" />
        </el-form-item>
        <el-form-item label="提现金额" prop="cashWithdrawal">
          <el-input v-model="form.cashWithdrawal" placeholder="请输入提现金额" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="uid">
          <el-select v-model="form.uid" placeholder="请选择用户编号" @change="fillRealName">
            <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" readonly disabled/>
        </el-form-item>
        <el-form-item label="银行卡号" prop="bankCardNumber">
          <el-input v-model="form.bankCardNumber" placeholder="请输入银行卡号" />
        </el-form-item>
        <el-form-item label="提现时间" prop="withdrawalRecord">
          <el-date-picker clearable v-model="form.withdrawalRecord" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择提现时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="提现状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择提现状态">
            <el-option v-for="withdrawalStatus in withdrawalStatuses" :key="withdrawalStatus.value"
              :label="withdrawalStatus.label" :value="withdrawalStatus.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Withdrawal">
import { listWithdrawal, getWithdrawal, delWithdrawal, addWithdrawal, updateWithdrawal } from "@/api/chy/withdrawal"
import { listMerchant } from "@/api/chy/merchant"
import { listUsers } from "@/api/gas/users"

const { proxy } = getCurrentInstance()


const withdrawalList = ref([])
const usersList = ref([])
const merchantList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantId: null,
    currentBalance: null,
    cashWithdrawal: null,
    realName: null,
    withdrawalRecord: null,
    status: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)
// 定义提现状态列表
const withdrawalStatuses = [
  { value: 0, label: '待审核', type: 'info' },
  { value: 1, label: '审核通过', type: 'success' },
  { value: 2, label: '审核拒绝', type: 'danger' },
  { value: 3, label: '已打款', type: 'primary' },
  { value: 4, label: '打款失败', type: 'warning' }
]
// 根据状态值获取状态标签
function getWithdrawalStatusLabel(status) {
  const item = withdrawalStatuses.find(s => s.value === status)
  return item ? item.label : '未知状态'
}
// 银行卡号掩码处理函数
function maskBankCardNumber(cardNumber) {
  if (!cardNumber) return '';
  // 截取前 4 位和后 4 位，中间用 * 替换
  return cardNumber.replace(/(\d{4})\d{8,}(\d{4})/, '$1****$2');
}
// 根据状态值获取标签类型
function getTagType(status) {
  const item = withdrawalStatuses.find(s => s.value === status)
  return item ? item.type : 'info'
}
// 定义填充真实姓名的函数
function fillRealName(uid) {
  const user = usersList.value.find(user => user.id === uid)
  if (user) {
    form.value.realName = user.userName
  } else {
    form.value.realName = ''
  }
}
/** 查询提现信息列表 */
function getList() {
  loading.value = true
  listWithdrawal(queryParams.value).then(response => {
    withdrawalList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 查询商户列表
function getMerchantList() {
  loading.value = true
  listMerchant(queryParams.value).then(response => {
    merchantList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getMerchantNameById(merchantId) {
  const merchant = merchantList.value.find(m => m.id === merchantId)
  return merchant ? merchant.name : ''
}
function getListUsers() {
  loading.value = true
  queryParams.value.params = {}
  listUsers(queryParams.value).then(response => {
    usersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getUserNameById(uid) {
  const user = usersList.value.find(user => user.id == uid)
  return user ? user.userName : '未知用户'
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    merchantId: null,
    currentBalance: null,
    cashWithdrawal: null,
    realName: null,
    bankCardNumber: null,
    withdrawalRecord: null,
    status: null
  }
  proxy.resetForm("withdrawalRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加提现信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getWithdrawal(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改提现信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["withdrawalRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateWithdrawal(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWithdrawal(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除提现信息编号为"' + _ids + '"的数据项？').then(function () {
    return delWithdrawal(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('chy/withdrawal/export', {
    ...queryParams.value
  }, `withdrawal_${new Date().getTime()}.xlsx`)
}

getList()
getMerchantList()
getListUsers()
</script>
